﻿using System;
using System.Diagnostics;
using System.Text;
using System.Globalization;
using System.IO;
using System.Xml.Linq;

namespace UnitDriven
{
	internal static class Extensions
	{
#if SILVERLIGHT || NETFX_CORE
		public static Exception Innermost(this Exception ex)
		{
			Exception innerMost = ex;
			while (innerMost.InnerException != null)
				innerMost = innerMost.InnerException;

			return innerMost;
		}

		public static string ToSummary(this TestContext context)
		{
			var doc = new XDocument();
			doc.AddFirst(new XElement("Summary"));
			if (context.HasError)
			{
				var globalErrors = new XElement("GlobalErrors");
				globalErrors.Add(context.Message);
				doc.Root.Add(globalErrors);
			}

			var results = new XElement("Results");
			results.Add(new XAttribute("Succeeded", context.Succeeded));
			results.Add(new XAttribute("Total", context.Total));
			doc.Root.Add(results);

			foreach (var item in context.Items)
			{
				item.ToSummary(results);
			}

			return doc.ToString();
		}

		private static void ToSummary(this IRunTests testRunner, XElement parent)
		{
			var group = testRunner as TestGroup;
			var method = testRunner as MethodTester;
			var type = testRunner as TypeTester;
			if (group != null)
			{
				var testGroup = new XElement("Group");
				parent.Add(testGroup);

				testGroup.Add(new XAttribute("Name", group.Name));
				testGroup.Add(new XAttribute("Succeeded", group.Succeeded));
				testGroup.Add(new XAttribute("Count", group.Items.Count));

				foreach (var item in group.Items)
					item.ToSummary(testGroup);

				return;
			}
			else if (type != null)
			{
				var testType = new XElement("Type");
				parent.Add(testType);

				testType.Add(new XAttribute("Name", type.Name));
				testType.Add(new XAttribute("Succeeded", type.Succeeded));
				testType.Add(new XAttribute("Count", type.Items.Count));

				foreach (var item in type.Items)
					item.ToSummary(testType);

				return;
			}
			else if (method != null)
			{
				var testMethod = new XElement("Method");
				parent.Add(testMethod);

				testMethod.Add(new XAttribute("Name", method.Name));
				testMethod.Add(new XAttribute("Status", method.Status));
				if (method.HasError)
					testMethod.Add(method.Message);

				return;
			}

			throw new NotSupportedException();
		}
#endif

		public static string ToDisplay(this object actual)
		{
			string act = null;

			if (actual != null)
				act = actual.ToString();

			if (act == null)
				act = "<null>";

			if (object.Equals(act, string.Empty))
				act = "string.Empty";

			return act;
		}

	}
}
